import 'dart:io';
import 'dart:typed_data';

import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/signature_entity.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:signature/signature.dart';
class SignLogic extends GetxController {
  final SignatureController signatureController = SignatureController();
  bool tmpIsEmpty = false;
  bool sinOK = false;
  SignatureData? signatureData = SignatureData();
  String path = "";
  /// todo：导出画板图片
  Future<String> exImg() async{
    // Directory tempDir = await getTemporaryDirectory();
    // String tempPath = tempDir.path;
    Uint8List? png = await signatureController.toPngBytes();
    Directory appDocDir = await getApplicationSupportDirectory();
    String appDocPath =  appDocDir.path+'/${DateTime.now().toIso8601String()} write sign.png';
    try{
      File(appDocPath).writeAsBytesSync(png!);
      path = appDocPath;
      update();
      return appDocPath;
    }catch (error){
      return "";
    }
  }

  /// todo：清空画板
  cleanSign(){
    signatureController.clear();
    path = "";
    update();
  }

  /// todo：监听器
  listener() {
    if (signatureController.value.length > 0) {
      tmpIsEmpty = true;
    } else {
      tmpIsEmpty = false;
    }
    update();
  }

  /// 获取电子签名
  getData(skuId) async{
    SignatureEntity signatureEntity = await DioService<SignatureEntity>().getSignature({"skuId":skuId});
    if(signatureEntity.code == 0) signatureData = signatureEntity.data;
    update();
  }

  /// 提交电子签名
  setSignature(orderId) async{
    SignatureEntity signatureEntity = await DioService<SignatureEntity>().submitSignature({
      "orderId": orderId,
      "signature": "http://m.ykimg.com/053500005EB27F464265870CD5EF0FE2?x-oss-process=image/resize,m_fill,w_270,h_152/quality,q_100",
      "signatureContractId": signatureData!.signatureContractId,
    });
    if(signatureEntity.code == 0) {
      update();
      Get.back(result: "提交了签名");
    }
  }
}
